package cool.qingqing.stream;

import org.junit.After;
import org.junit.Before;
import org.testng.annotations.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;

/**
 * @author 高山青
 * @Date 2022/1/3  -   20:26
 */
public class StreamDemo01 {
	/**
	 * 串行流
	 */
	@Test
	public void test01(){
		//可以看出来都是单线程操作
		Stream.of("11","14","53","24").map(s -> {
			System.out.println(Thread.currentThread().getName()+"这个值是："+s);
			return s;
		}).count();
	}

	/**
	 * 获取并行流额两种方式
	 */
	@Test
	public void test02(){
		List<Integer> list=new ArrayList<>();
		list.parallelStream();

		Stream.of(1,2,45,6).parallel();
	}

	/**
	 * 并行流操作
	 */
	@Test
	public void test03(){
		Stream.of(1,2,45,6).parallel().map(i -> {
			System.out.println(Thread.currentThread().getName()+"   i="+i);
			return i;
		}).count();
	}
	   long start;
	@Before
	public void before(){
		start=System.currentTimeMillis();
	}
	@After
	public void after(){
		long end = System.currentTimeMillis();
		System.out.println("用时："+(end-start));
	}

	/**
	 * 求和对比,串流操作
	 */
	@Test
	public void test04(){
		LongStream.rangeClosed(0,100000000).reduce(0,Long::sum);
	}

	/**
	 * for循环的
	 */
	@Test
	public void test05(){
		long sum=0;
		for (int i = 0; i <100000000 ; i++) {
			sum+=i;
		}
	}
	/**
	 * 并行的
	 */
	@Test
	public void test06(){
		LongStream.rangeClosed(0,100000000).parallel().reduce(0,Long::sum);
	}

	/**
	 * 线程安全问题
	 */
	@Test
	public void test07(){
		//解决线程安全问题
		IntStream.rangeClosed(0,1000).parallel().boxed().collect(Collectors.toList());

	}
	@Test
	public void test08(){
		List<Integer> list=new ArrayList<>();
		for (int i = 0; i < 1000; i++) {
			list.add(i);
		}
	}

	@Test
	public void test09(){
		Stream<Integer> astream = Stream.of(13, 45, 56, 34).map(a -> {
			System.out.println("a的值是："+a);
			return  a * a;});
		System.out.println("让我看一下："+astream.getClass().getTypeName());
		astream.forEach(System.out::println);

	}
}
